﻿using ASmile.Com.DictCom;
using ASmile.DBModel;
using ASmile.Extend;
using ASmile.ORM.Cores;

namespace ASmile.Com.Da
{
    public class DictComBLL : BLLCrudBase<ArgDictSearch, Dict_Common>, IDictComBLL //IBLLCrud<ArgDictSearch, Dict_Common>
    {
        public ApiResultList<Dict_CommonType> GetDictTypes(string searchVal)
        {
            return new DictComTypeBLL().GetList(new ArgPageData { SearchVal = searchVal });
        }

        protected override void SetQuery(QueryCondition<Dict_Common> query, ArgDictSearch arg)
        {
            query.WhereAnd(s => s.IsEnable == true);
            if (arg.DictType != null)
            {
                query.WhereAnd(s => s.DictType == arg.DictType.Value);
            }
            if (arg.SearchVal.IsNotEmpty())
            {
                string likeStr = $"%{arg.SearchVal}%";
                query.WhereAnd(s =>
                    s.WEx_Like(s.DictTypeName, likeStr) ||
                    s.WEx_Like(s.DictValue, likeStr) ||
                    s.WEx_Like(s.DictValuePY, likeStr)
                    );
            }
            query.OrderBy(s => s.DictType).OrderBy(s => s.DictValueOrderNo);
        }

        protected override ApiResult<string> VerifyModel(Dict_Common model, bool isAdd)
        {
            if (model.DictType <= 0)
            {
                return RetErr("DictType", "字典类型错误");
            }
            if (model.DictCode.IsEmpty())
            {
                return RetErr(nameof(model.DictCode), "字典代码不能为空");
            }
            if (model.DictType == 0)
            {
                return RetErr(nameof(model.DictTypeName), "字典类型选择错误");
            }
            if (isAdd)
            {
                if (DB.QueryExist<Dict_Common>(s =>
                    s.DictType == model.DictType &&
                    s.DictCode == model.DictCode))
                {
                    return RetErr(nameof(model.DictCode), "字典值已经存在");
                }
                model.Id = NewId();
                return RetOK(model.Id, "新增成功");
            }
            else
            {
                model.ClearChangedState(Dict_Common.CNDictType, Dict_Common.CNIsEnable, Dict_Common.CNDictCode);
            }

            return RetOK("", "保存成功");
        }
        /// <summary>
        /// 更新排序值
        /// </summary>
        public ApiResult SetSortNo(ArgSetSortNo arg)
        {
            Dict_Common m = new Dict_Common
            {
                Id = arg.Id,
                DictValueOrderNo = arg.SortNo
            };

            var ret = DB.Update(m);
            if (ret.RowCount == 1)
            {
                return RetOK($"设置排序成功，{arg.SortNo}");
            }
            return RetErr("设置排序失败");
        }
    }
}